import { Form, Table, Input, Button, message } from "antd";
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { ColumnsType } from "antd/es/table";
import { useForm } from "antd/es/form/Form";
import "./index.less";
import { getUserInfo } from "@/utils";

import { AddFriendModal } from "./AddFriendModal";

import { createOneToOne, findChatroom, friendshipList } from "@/api/friendship";

interface SearchParams {
    name: string;
}
interface FriendshipSearchResult {
    id: number;
    username: string;
    nickName: string;
    headPic: string;
    email: string;
}

export function Friendship() {
    const navigate = useNavigate();
    const [form] = useForm();
    const [friendshipResult, setFriendshipResult] = useState<Array<FriendshipSearchResult>>([]);
    const [isAddFriendModalOpen, setAddFriendModalOpen] = useState<boolean>(false);

    const columns: ColumnsType<FriendshipSearchResult> = [
        {
            title: 'ID',
            dataIndex: 'id'
        },
        {
            title: '用户名',
            dataIndex: 'username'
        },
        {
            title: '昵称',
            dataIndex: 'nickName'
        },
        {
            title: '头像',
            dataIndex: 'headPic',
            render: (_, record) => (
                <div>
                    <img src={record.headPic} />
                </div>
            )
        },
        {
            title: '邮箱',
            dataIndex: 'email'
        },
        {
            title: '操作',
            render: (_, record) => (
                <div>
                    <a href="#" onClick={() => { goToChat(record.id) }}>聊天</a>
                </div>
            )
        }
    ]

    const searchFriendList = async (values: SearchParams) => {
        try {
            const resp: any = await friendshipList(values.name);
            setFriendshipResult(resp.map((item: FriendshipSearchResult) => {
                return {
                    ...item,
                    key: item.id
                }
            }))
        } catch (error: any) {
            message.error(error?.data?.message || '系统繁忙，请稍后重试');
        }
    }
    const goToChat = async (friendId: number) => {
        const userId = getUserInfo().id;
        try {
            const resp = await findChatroom(userId, friendId);
            if (resp) {
                navigate('/chat', { state: { chatroomId: resp } })
            } else {
                const resp2 = await createOneToOne(friendId);
                navigate('/chat', { state: { chatroomId: resp2 } });
            }
        } catch (error: any) {
            message.error(error?.data?.message || '系统繁忙，请稍后重试');
        }
    }

    useEffect(() => {
        searchFriendList({
            name: form.getFieldValue('name')
        });
    }, []);


    return <div className="friendship">
        <div className="friendship_form">
            <Form
                form={form}
                layout="inline"
                colon={false}
                onFinish={searchFriendList}
            >
                <Form.Item label="名称" name='name'><Input /></Form.Item>
                <Form.Item label=" "><Button type="primary" htmlType="submit">搜索</Button></Form.Item>
                <Form.Item label=" "><Button type="primary" style={{ background: 'green' }} onClick={() => { setAddFriendModalOpen(true) }}>添加好友</Button></Form.Item>
            </Form>
        </div>
        <div className="friendship_table">
            <Table columns={columns} dataSource={friendshipResult}></Table>
        </div>

        <AddFriendModal isOpen={isAddFriendModalOpen} handleClose={() => { setAddFriendModalOpen(false) }} />
    </div>
}